<template>
  <a-modal
    title="編輯供應商"
    :width="760"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleSubmit"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading" style="padding:15px 25px;">
      <a-form :form="form" v-bind="formLayout">
        <a-row class="form-row" :gutter="48">
          <div v-for="(v, k) in fields" :key="k">
            <a-col :lg="12" :md="12" :sm="24">
              <a-form-item :label="v.label">
                <template v-if="v.type == 'select'">
                  <a-select
                    v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]"
                    @change="v.onChange">
                    <a-select-option :key="sk" v-for="(item,sk) in selectList[v.listName]" :value="v.listValue?item[v.listValue]:item">{{
                      item[v.listLabel]}}
                    </a-select-option>
                  </a-select>
                </template>
                <template v-else-if="v.type == 'textarea'">
                  <a-textarea :auto-size="{ minRows: 5, maxRows: 10 }" v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]"/>
                </template>
                <template v-else-if="v.type == 'password'">
                  <a-input-password v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]" placeholder="請輸入密碼"/>
                </template>
                <template v-else-if="v.type == 'upload'">
                  <a-upload
                    name="file"
                    :showUploadList="false"
                    :customRequest="upload"
                  >
                    <a-button> <a-icon type="upload" /> Click to Upload </a-button>
                  </a-upload>
                  <span v-if="model!==null">{{ model[v.key] }}</span>
                </template>
                <template v-else-if="v.type == 'date'">
                  <a-date-picker valueFormat="yyyy-MM-DD" v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]" />
                </template>
                <template v-else-if="v.type == 'number'">
                  <a-input v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required, min: 0, message: v.message, type: 'number',transform(value){return Number(value)}}]}]"/>
                </template>
                <template v-else>
                  <a-input v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required, min: 0, message: v.message}]}]"/>
                </template>
              </a-form-item>
            </a-col>
          </div>
        </a-row>
      </a-form>
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">添加貨品</a-button>
      </div>
      <a-table :columns="columns" :data-source="data" :pagination="false">
        <a slot="name" slot-scope="text">{{ text }}</a>
        <span slot="customTitle"><a-icon type="smile-o" /> Name</span>
        <span slot="tags" slot-scope="tags">
          <a-tag
            v-for="tag in tags"
            :key="tag"
            :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
          >
            {{ tag.toUpperCase() }}
          </a-tag>
        </span>
        <span slot="action" slot-scope="text, record ,index">
          <a @click="handleDelete(index)">删除</a>
        </span>
      </a-table>
    </a-spin>
    <create-form-goods
      ref="createModal"
      :visible="visibleGoods"
      :model="mdlGoods"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </a-modal>
</template>

<script>
import { _put, _getAllSupplierGoodsByIdSup } from '@/api/supplier'
import CreateFormGoods from './supplierGoods'
// 表单字段
const fields = [
  { key: 'no', label: '編號', required: true, message: '' },
  { key: 'name', label: '名稱', required: true, message: '' },
  { key: 'phone', label: '電話', required: true, message: '' },
  { key: 'contactPerson', label: '聯絡人', required: true, message: '' },
  { key: 'email', label: 'Email', required: true, message: '' },
  { key: 'fax', label: 'Fax', required: true, message: '' },
  { key: 'remark', label: '備註', required: true, message: '', type: 'textarea' },
  { key: 'paymentMethod', label: '支付方式', required: true, message: '', type: 'select', listName: 'paymentMethodList', listValue: 'value', listLabel: 'label' },
  { key: 'address', label: '地址', required: true, message: '' },
  { key: 'whatsapp', label: 'Wahtsapp', required: true, message: '' },
  { key: 'website', label: '網址', required: true, message: '' },
  { key: 'severalPeriods', label: '數期', required: true, message: '' },
  { key: 'type', label: '類型', required: true, message: '', type: 'select', listName: 'typeList', listValue: 'value', listLabel: 'label' }
]

const columns = [
  {
    title: '貨品名稱',
    dataIndex: 'name'
  },
  {
    title: '貨品類別',
    dataIndex: 'category'
  },
  {
    title: '類型',
    dataIndex: 'type',
    customRender: (data) => {
      if (data === 0) {
        return '普通貨品'
      } else {
        return '鮮活貨品'
      }
    }
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  components: {
    CreateFormGoods
  },
  data () {
    this.formLayout = {
    }
    return {
      form: this.$form.createForm(this),
      fields: fields,
      loading: false,
      selectList: {
        typeList: [{ label: '普通供應商', value: 0 }, { label: '鮮活供應商', value: 1 }],
        paymentMethodList: [{ label: '現金', value: 0 }, { label: '轉賬', value: 1 }]
      },
      data: [],
      columns,
      visibleGoods: false,
      mdlGoods: null
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach((v, i) => this.form.getFieldDecorator(v.key))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model.idSup', () => {
      _getAllSupplierGoodsByIdSup(this.model.idSup).then((ret) => {
        this.data = ret.data
      })
    })
  },
  methods: {
    // handler
    handleSubmit (e) {
      e.preventDefault()
      this.$emit('handleRefresh')
      this.form.validateFields((err, values) => {
        // 判断是否有填货品
        if (this.data.length <= 0) {
          alert('请填写货品！')
          return
        }
        if (!err) {
          // 新增
          this.loading = true
          values['idSup'] = this.model.idSup
          values['supplierListStr'] = JSON.stringify(this.data)
          _put(values).then((res) => this.handleSuccess(res))
        }
      })
    },
    handleSuccess (ret) {
      this.loading = false
      if (ret.code === 0) {
          this.form.resetFields()
          this.$emit('cancel')
          this.$message.info(ret.msg)
          this.data = []
      } else {
        this.$message.error('res.msg')
      }
    },
    handleAdd () {
      this.mdlGoods = null
      this.visibleGoods = true
    },
    handleDelete (index) {
      this.visibleGoods = false
      this.data.splice(index, 1)
    },
    handleCancel () {
      this.visibleGoods = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
      this.data = []
    },
    handleOk (data) {
      this.data.push(data)
      this.visibleGoods = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    }
  }
}
</script>
